<?

class BandMemberList extends db {
	function get_band_members() {
		$query = 'select Band_Members.ID from Band_Members inner join Users on (Band_Members.user_id = Users.ID) order by Users.lastname asc';
		$r = mysql_query($query);		
		if ($r) { 
			$bm = array();
			while ($row = mysql_fetch_assoc($r)) {
				$bm[] = BandMember::get($row['ID']);
			}
			return $bm;
		} else {
			$e = new Error();
			$e->add(mysql_error());
			return $e;		
		}
	}
	
	function get_active_band_members() {
		$query = 'select Band_Members.ID from Band_Members inner join Users on (Band_Members.user_id = Users.ID) where Band_Members.is_active = 1 order by Users.lastname asc';
		$r = mysql_query($query);		
		$members = array();
		if ($r) {
			while ($row = mysql_fetch_assoc($r)) {
				$members[] = BandMember::get($row['ID']);
			}
			return $members;
		} else {
			$e = new Error();
			$e->add(mysql_error());
			return $e;
		}		
	}
}


class BandMember extends db {

	var $ID, $is_active, $username, $password, $role, $equipment, $birthdate, $user_id, $influences, $bio, $av_area_id, $photo_area_id;
	
	function getID() { return $this->ID; }
	function isActive() {return $this->is_active;}
	function getRole() {return $this->role;}
	function getEquipment() {return $this->equipment;}
	function getInfluences() {return $this->influences;}
	function getBio() {return $this->bio;}
	function getAVAreaID() {return $this->av_area_id;}
	function getAVAreaObject() {
		if ($this->av_area_id > 0) {
			$ma = MediaArea::get($this->av_area_id);
			return $ma;
		} else {
			$e = new Error();
			$e->add("An administrator has not yet registered this band member for audio or videos.");
			return $e;
		}
	}
	function getPhotoAreaID() {return $this->photo_area_id;}
	function getPhotoAreaObject() {
		if ($this->photo_area_id > 0) {
			$ma = MediaArea::get($this->photo_area_id);
			return $ma;
		} else {
			$e = new Error();
			$e->add("An administrator has not yet registered this band member for photos.");
			return $e;
		}
	}
	function getUserID() {return $this->user_id;}
	function getUserObject() {
		$uo = User::get($this->user_id);
		return $uo;
	}
	function getTotalDiaryEntries() {
		$q = "select count(ID) as total from Band_Diaries where member_id = '{$this->ID}'";
		$r = mysql_query($q);
		$row = mysql_fetch_assoc($r);
		if ($row['total']) {
			return $row['total'];
		} else {
			return 0;
		}
	}
	function getLatestDiaryObject() {
		$q = "select ID from Band_Diaries where member_id = '{$this->ID}' order by date_time desc limit 1";
		$r = mysql_query($q);
		$row = mysql_fetch_assoc($r);
		if ($row['ID']) {
			return BandMemberDiary::get($row['ID']);
		}
	}
	function getDiaries() {
		$args_list = func_get_args();
		$number_to_get = (int) $args_list[0];
		$start_number = (int) $args_list[1];		
			
		if ($number_to_get && $start_number) {
			$query = "select ID from Band_Diaries where member_id = {$this->ID} order by date_time desc limit $start_number, $number_to_get";
		} else if ($number_to_get) {
			$query = "select ID from Band_Diaries where member_id = {$this->ID} order by date_time desc limit 0, $number_to_get";
		} else if ($start_number) {
			$query = "select ID from Band_Diaries where member_id = {$this->ID} order by date_time desc limit $start_number, 10";
		} else {
			$query = "select ID from Band_Diaries where member_id = {$this->ID} order by date_time desc limit 0, 10";
		}
		
		$r = mysql_query($query);
		$diaries = array();
		while ($row = mysql_fetch_assoc($r)) {
			$diaries[] = BandMemberDiary::get($row['ID']);
		}
		return $diaries;
	}
	
	function getByUserID($userID) {
		if (is_numeric($userID) && $userID > 0) {
			$q = "select ID from Band_Members where user_id = {$userID}";
			$r = mysql_query($q);
			if ($r) {
				$row = mysql_fetch_assoc($r);
				return BandMember::get($row['ID']);			
			} else {
				return Error::MySQL();
			}
		} else {
			return Error::create("Invalid user ID.");
		}		
	}
	
	function get($bmeID) {
		$db = new db;
		if ($bmeID > 0) {
			$q = "select ID, role, equipment, influences, bio, av_area_id, photo_area_id, is_active, user_id from Band_Members where ID = {$bmeID}";
			$r = mysql_query($q);
			$row = mysql_fetch_assoc($r);
		
			$bme = new BandMember;
			if ($row['ID']) {
				$bme->ID = $row['ID'];
				$bme->role = $db->sanitize_from_db($row['role']);
				$bme->equipment = $db->sanitize_from_db($row['equipment']);
				$bme->influences = $db->sanitize_from_db($row['influences']);
				$bme->bio =  $db->sanitize_from_db($row['bio']);
				$bme->av_area_id = $row['av_area_id'];
				$bme->photo_area_id = $row['photo_area_id'];
				$bme->is_active = $row['is_active'];
				$bme->user_id = $row['user_id'];
				
				return $bme;
			}
		}
		
		$e = new Error();
		$e->add("Please specify a valid band member ID.");
		return $e;
	}
	
	function add($postArray) {
		$db = new db;
		$e = new Error();
		if (User::isAdmin()) {			
			$password = $db->sanitize_to_db($postArray['password']);
			$confirmPassword = $db->sanitize_to_db($postArray['password_confirm']);
			$passwordHash = null;
			
			$username = $db->sanitize_to_db($postArray['username']);
			if ($username != null && $username != "") {
				if (User::exists($username)) {
					$e->add("A user with the username '{$username}' already exists.");
				}
			} else {
				$e->add("A band member entry must contain a username.");
			}
			
			if ($password != null && $password != "") {
				// something has been entered for password
				if ($password == $confirmPassword) {
					if (strlen($password) > 4) {	
						$passwordHash = md5($password);
					} else {
						$e->add("A user password must be at least 5 characters.");
					}
				} else {
					$e->add("The two passwords do not match.");
				}
			} else {
				$e->add("A band member entry must contain a password.");
			}
			
			$firstname = $db->sanitize_to_db($postArray['firstname']);
			if (!$firstname) {
				$e->add("A band member entry must contain a first name.");
			}
			
			$lastname = $db->sanitize_to_db($postArray['lastname']);
			$role = $db->sanitize_to_db($postArray['role']);
			if (!$role) {
				$e->add("A band member entry must contain a role.");
			}
			
			$_dt = strtotime($db->sanitize_to_db($postArray['birthdate']));
			$birthdate = date('Y-m-d', $_dt);
			$email = $db->sanitize_to_db($postArray['email']);
			$equipment = $db->sanitize_to_db($postArray['equipment']);
			$influences = $db->sanitize_to_db($postArray['influences']);
			$bio = $db->sanitize_to_db($postArray['bio']);
			
			if ($e->hasErrors()) {
				return $e;
			} else {
				$result = @mysql_query("insert into Users (username, password, lastname, firstname, email, birthdate) values ('$username', '$passwordHash', '$lastname', '$firstname', '$email', '$birthdate')");
				if (!$result) {
					$e->add(mysql_error());
				} else {
					$userID = mysql_insert_id();
					$result2 = @mysql_query("insert into Band_Members (role, equipment, influences, bio, user_id) values ('{$role}', '{$equipment}', '{$influences}', '{$bio}', {$userID})");
					if (!$result2) {
						$e->add(mysql_error());
					} else {
						$bmID = mysql_insert_id();
					}
				}
				
				if ($e->hasErrors()) {
					return $e;
				} else {
					$bm = BandMember::get($bmID);
					return $bm;
				}
			}			
			
		} else {
			$e->add('You may not add a band member entry. Only an admin user may do that.');
			return $e;
		}
	}	
	
	function update($postArray) {
		$db = new db;
		$e = new Error();
		if ($this->canEdit()) {
			$password = $db->sanitize_to_db($postArray['password']);
			$confirmPassword = $db->sanitize_to_db($postArray['password_confirm']);
			$passwordHash = null;
			if ($password != null && $password != "") {
				// something has been entered for password
				if ($password == $confirmPassword) {
					if (strlen($password) > 4) {	
						$passwordHash = md5($password);
					} else {
						$e->add("A user password must be at least 5 characters.");
					}
				} else {
					$e->add("The two passwords do not match.");
				}
			}
						
			$firstname = $db->sanitize_to_db($postArray['firstname']);
			if (!$firstname) {
				$e->add("A band member entry must contain a first name.");
			}
			
			$lastname = $db->sanitize_to_db($postArray['lastname']);
			
			$role = $db->sanitize_to_db($postArray['role']);
			if (!$role) {
				$e->add("A band member entry must contain a role.");
			}
			
			$email = $db->sanitize_to_db($postArray['email']);			
			$_dt = strtotime($db->sanitize_to_db($postArray['birthdate']));
			$birthdate = date('Y-m-d', $_dt);			
			$equipment = $db->sanitize_to_db($postArray['equipment']);
			$influences = $db->sanitize_to_db($postArray['influences']);
			$bio = $db->sanitize_to_db($postArray['bio']);
			
			if ($e->hasErrors()) {
				return $e;
			} else {
				// first we update the users record
				$passwordQuery = ($passwordHash != null) ? "password = '{$passwordHash}'," : "";
				
				$result = @mysql_query("update Users set {$passwordQuery} lastname='$lastname', firstname='$firstname', birthdate='$birthdate', email='$email' where ID = {$this->user_id}");
				if (!$result) {
					$e->add(mysql_error());
				}
				$result2 = mysql_query("update Band_Members set role='$role', equipment='$equipment', influences='$influences', bio='$bio' where ID = " . $this->ID);
				if (!$result2) {
					$e->add(mysql_error());
				}
				if ($e->hasErrors()) {
					return $e;
				} else {
					return true;
				}
			}
		} else {
			$e->add("You may not edit this band member's information.");
			return $e;
		}
	}
	
	function getMemberPhoto() {
		// the album cover is actually the first piece of media that's active in a given member's media area
		// first we get the media area ID for the given release.
		if ($this->photo_area_id) {
			// if we have an area ID, we continue
			$q = "select ID from DarkRoom_Media_to_Areas where area_id = {$this->photo_area_id} and is_active = 1 order by display_order asc limit 1";
			$r = mysql_query($q);
			if (!$r) {
				return Error::MySQL();
			}
			$row = mysql_fetch_assoc($r);
			if ($row['ID']) {
				$mi = MediaInstance::get($row['ID']);
				return $mi;
			}
		}
	}
	
	function deactivate() {
		$e = new Error();
		if (User::isAdmin()) {
			if (!@mysql_query("update Band_Members set is_active = 0 where ID = " . $this->ID)) {
				$e->add(mysql_error());
				return $e;
			} else {
				return true;
			}
		} else {
			$e->add('You may not deactivate this band member.');
			return $e;
		}
	}
	
	function activate() {
		$e = new Error();
		if (User::isAdmin()) {
			if (!@mysql_query("update Band_Members set is_active = 1 where ID = " . $this->ID)) {
				$e->add(mysql_error());
				return $e;
			} else {
				return true;
			}
		} else {
			$e->add('You may not activate this band member.');
			return $e;			
		}
	}
	
	function remove() {
		$e = new Error();
		if (User::isAdmin()) {
			if (!@mysql_query("delete from Band_Members where ID = " . $this->ID)) {
				$e->add(mysql_error());
				return $e;
			} else {
				return true;
			}
		} else {
			$e->add('You may not remove this band member.');
			return $e;			
		}
	}
	
	function registerMedia($mediaType) {
		$type = ($mediaType == 'av') ? 'av' : 'photos';
		$e = new Error();
		if (User::isAdmin()) {
			if (($type == 'av' && $this->av_area_id < 1) || ($type == 'photos' && $this->photo_area_id < 1)) {
				$areaTitle = ($type == 'av') ? "Band Member Audio/Video: " : "Band Member Photos: ";
				$areaIDField = ($type == 'av') ? "av_area_id" : "photo_area_id";
				if ($type == 'av') {
					$allowed_extensions = MEDIA_EXTENSIONS_ALLOWED_AV;
					$display = "list";
				} else {
					$allowed_extensions = MEDIA_EXTENSIONS_ALLOWED_PHOTO;
					$display = "grid";
				}
				$uo = $this->getUserObject();
				
				$ma = MediaArea::add(0, $areaTitle . $uo->getFirstName() . ' ' . $uo->getLastName(), null, $allowed_extensions, $display);
				$ma->activate();
				$q = "update Band_Members set {$areaIDField} = " . $ma->getID() . " where ID = {$this->ID}";
				$r = mysql_query($q);
				if (!$r) {
					$e->add(mysql_error());
					return $e;
				} else {
					return $r;
				}
			} else {
				$e->add("A band member with an ID of {$this->ID} is already registered.");
				
			}
		} else {
			$e->add('Only an admin user may authorize a member for media.');
			return $e;	
		}
	}
	
	function validateMediaOperation($opType = "ADD", $mediaObject = null) {
		$e = new Error();
		
		// called automatically by the m2 functions that add media, when passed the object
		// opType allows us to distinguish between adding, editing, updating, etc... but most times
		// the same check will work for all operation types
		if ($opType == "RESCAN") {
			// non-admins can't delete, only deactivate
			if (!User::isAdmin()) {
				$e->add('Only an admin user may rescan band member media.');
				return $e;
			} else {
				return true;
			}
		} else if ($opType == "DELETE") {
			// non-admins can't delete, only deactivate
			if (!User::isAdmin()) {
				$e->add('Only an admin user may delete band member media.');
				return $e;
			} else {
				return true;
			}
		} else if (!$this->canEdit()) {
			$e->add('Only an admin user may add to or modify the media of another band member.');
			return $e;
		} else {
			return true;
		}
		exit;
	}
	
	function canEdit() {
		$uo = User::getCurrent();
		if (is_object($uo)) {
			return ($uo->getID() == $this->getUserID() || $uo->isAdmin());
		}
	}
	
}
?>